package com.sunday.common.leaf.study.operation;

import com.sunday.common.core.gson.GsonUtils;
import com.sunday.common.leaf.enums.Status;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class CountUtils {

    private final long twepoch = 1288834974657L;
    private final long sequenceBits = 12L;

    private final long sequenceMask = ~(-1L << sequenceBits);
    // 同一时间的序列
    private long sequence = 0L;
    private long lastTimestamp = -1L;
    private static final Random RANDOM = new Random();

    public synchronized Result get() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) {
                try {
                    wait(offset << 1);
                    timestamp = timeGen();
                    if (timestamp < lastTimestamp) {
                        return new Result(-1, Status.EXCEPTION);
                    }
                } catch (InterruptedException e) {
                    log.error("[Snowflake] wait interrupted");
                    return new Result(-2, Status.EXCEPTION);
                }
            } else {
                return new Result(-3, Status.EXCEPTION);
            }
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                //seq 为0的时候表示是下一毫秒时间开始对seq做随机
                sequence = RANDOM.nextInt(100);
                timestamp = tilNextMillis(lastTimestamp);
            }
            log.info("{}", sequence);
        } else {
            //如果是新的ms开始
            sequence = RANDOM.nextInt(100);
            log.info("{}", sequence);
        }
        lastTimestamp = timestamp;
        long id = ((timestamp - twepoch) << sequenceBits) | sequence;
        return new Result(id, Status.SUCCESS);

    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public long getTimestamp(long id) {
        return (id >> sequenceBits) + twepoch;
    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Result {

        private long id;

        private Status status;

        @Override
        public String toString() {
            return GsonUtils.SERIALIZE_NULL.toJson(this);
        }

    }


}
